//
//  ReportViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/4/1.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class ReportViewController: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate,UITextViewDelegate, AJPhotoPickerProtocol, AJPhotoBrowserDelegate {
    
    
    var contentField: UITextView!
    var placeholderLabel: UILabel!
    var photoCollectionView: UICollectionView!
    
//    var photoArray = [UIImage]()
    var photoArray = NSMutableArray()
    
    let collectionIdentifier = "PhotoCollectionViewCellIdentifier"
    
    var hud: MBProgressHUD!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "提交", style: UIBarButtonItemStyle.done, target: self, action: #selector(OpinionViewController.send))
        
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.title = "举报投诉"
        
        
//        photoArray.append(UIImage.init(named: "hnx")!)
        
        InitViews()
        
    }
    
    func send() {
        hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.mode = MBProgressHUDMode.indeterminate
        hud.labelText = "正在提交...请稍后"
        let queue = DispatchQueue(label: "queue")
        queue.async {
            sleep(3)
            DispatchQueue.main.async(execute: {
                self.hud.hide(true)
                self.navigationController?.popViewController(animated: true)
            })
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        contentField.resignFirstResponder()
    }
    func InitViews() {
        //++++++++++++++++++++++++++++++++++++++++++
//        contentField = FUITextField.init(frame: CGRect(x: 10, y: 74, width: screenW - 20, height: 100))
//        contentField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1).cgColor
//        contentField.layer.borderWidth = 1
//        contentField.layer.cornerRadius = 3
//        contentField.borderColor = barColor
//        contentField.borderWidth = 2.0
//        contentField.cornerRadius = 3
//        contentField.textFieldColor = UIColor.white
//        contentField.backgroundColor = UIColor.clear
//        contentField.font = UIFont.systemFont(ofSize: 14)
//        contentField.placeholder = "提交您所要举报的内容（100字内）"
//        contentField.edgeInsets = UIEdgeInsetsMake(2.0, 8.0, 2.0, 8.0)
//        self.view.addSubview(contentField)
        //++++++++++++++++++++++++++++++++++++++++++
        contentField = UITextView.init(frame: CGRect(x: 10, y: 74, width: screenW - 20, height: 100))
        
        contentField.backgroundColor = UIColor.init(hexString: "f2f2f2", alpha: 1)
        contentField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        contentField.layer.borderWidth = 1
        contentField.layer.cornerRadius = 3
        contentField.isScrollEnabled = true
        contentField.textColor = UIColor.darkGray
        contentField.isHidden = false
        contentField.delegate = self
        contentField.font = UIFont.systemFont(ofSize: 15)
        
        placeholderLabel = UILabel.init(frame: CGRect(x: contentField.frame.minX + 4, y: contentField.frame.minY + 7, width: screenW - 20 - 8, height: 20))
        placeholderLabel.text = "提交您所要举报的内容（100字内)"
        placeholderLabel.textColor = UIColor.init(hexString: "DBDBDB", alpha: 1.0)
        placeholderLabel.isEnabled = false
        placeholderLabel.backgroundColor = UIColor.clear
        placeholderLabel.font = UIFont.systemFont(ofSize: 15.0)

        self.view.addSubview(contentField)
        self.view.addSubview(placeholderLabel)
        
        //+++++++++++++
        
        
        photoCollectionView = UICollectionView.init(frame: CGRect(x: 10, y: contentField.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray as NSArray)), collectionViewLayout: AddPhotoFlowLayout.init())
        photoCollectionView.backgroundColor = UIColor.clear
        photoCollectionView.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: collectionIdentifier)
        photoCollectionView.scrollsToTop = true
        photoCollectionView.delegate = self
        photoCollectionView.dataSource = self
        self.view.addSubview(photoCollectionView)
        
    }
    
    //MARK: - collection view delegate and data source
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoArray.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: PhotoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionIdentifier, for: indexPath) as! PhotoCollectionViewCell
        cell.backgroundColor = UIColor.white
        let count = (indexPath as NSIndexPath).row
        if count == photoArray.count {
            cell.photoImage.image = UIImage.init(named: "hnx")
        }else{
            let assest = photoArray.object(at: count)
            if (assest as AnyObject).isKind(of: UIImage.self) {
                cell.photoImage.image = assest as? UIImage
            }else{
                let ass = assest as! ALAsset
                cell.photoImage.image = UIImage.init(cgImage: ass.aspectRatioThumbnail().takeUnretainedValue())
            }
        }
        
        return cell;
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        contentField.resignFirstResponder()
        if (indexPath as NSIndexPath).row == photoArray.count {
            photoAdd()
        }else {
            print("选中第\(indexPath.row+1)张")
            //++++++++++++++++++++++++++++++++
            showBigImage(index: Int(indexPath.row))
        }
    }
    
    //MARK: - AJPhotoPickerProtocol
    
    //选择完成
    
    func photoPicker(_ picker: AJPhotoPickerViewController!, didSelectAssets assets: [Any]!) {
        photoArray.removeAllObjects()
        photoArray.addObjects(from: assets)
        
        photoCollectionView.frame = CGRect(x: 10, y: contentField.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray))
        photoCollectionView.reloadData()
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    func photoPicker(_ picker: AJPhotoPickerViewController!, didSelect asset: ALAsset!) {
        //点击选中
    }
    
    func photoPicker(_ picker: AJPhotoPickerViewController!, didDeselect asset: ALAsset!) {
        //取消选中
    }
    
    //点击相机按钮相关操作
    
    func photoPickerTapCameraAction(_ picker: AJPhotoPickerViewController!) {
        
        if photoArray.count >= 9 {
            TSMessage.showNotification(in: picker, title: "提示", subtitle: "对不起，您选择的图片过多，现在只能支持最大9张图片", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
        }else{
            picker.dismiss(animated: false, completion: nil);
            let pickCamer = UIImagePickerController()
            pickCamer.allowsEditing = false
            pickCamer.sourceType = UIImagePickerControllerSourceType.camera
            pickCamer.delegate = self
            pickCamer.cameraFlashMode = UIImagePickerControllerCameraFlashMode.auto
            self.present(pickCamer, animated: true, completion: nil)
        }
        
    }
    
    //取消选择照片
    func photoPickerDidCancel(_ picker: AJPhotoPickerViewController!) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    //超过最大选择项时
    
    func photoPickerDidMaximum(_ picker: AJPhotoPickerViewController!) {
        TSMessage.showNotification(in: picker, title: "提示", subtitle: "对不起，您选择的图片过多，现在只能支持最大9张图片", image: nil, type: TSMessageNotificationType.error, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
    }
  
    //MARK: - AJPhotoBrowserDelegate
    func photoBrowser(_ vc: AJPhotoBrowserViewController!, deleteWith index: Int) {
        //删除选中的照片
    }
    func photoBrowser(_ vc: AJPhotoBrowserViewController!, didDonePhotos photos: [Any]!) {
        //从相册点击确定
        self.photoArray.removeAllObjects()
        self.photoArray.addObjects(from: photos)
        
        self.photoCollectionView.reloadData()
        vc.dismiss(animated: true, completion: nil)
        
    }
    func showBigImage(index: Int) {
        var pphotos = [Any]()
        for i in 0..<photoArray.count {
            print("\(i) = \(photoArray.object(at: i))")
            pphotos.append(photoArray[i])
        }
        
        let photoBrowserVC = AJPhotoBrowserViewController.init(photos: pphotos, index: index)
        photoBrowserVC?.delegate = self
        self.present(photoBrowserVC!, animated: true, completion: nil)
    }
    
    func photoAdd() {
        /*
        let actionSheet: UIActionSheet!
        actionSheet = UIActionSheet.init(title: "添加图片", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: "拍照", otherButtonTitles: "从相册中选择")
        actionSheet.actionSheetStyle = UIActionSheetStyle.default
        actionSheet.show(from: self.view.frame, in: self.view, animated: true)
        */
        
        let picker = AJPhotoPickerViewController.init()
        picker.maximumNumberOfSelection = 9
        picker.multipleSelection = true
        picker.assetsFilter = ALAssetsFilter.allPhotos()
        picker.showEmptyGroups = true
        picker.delegate = self
        self.present(picker, animated: true, completion: nil)
    }
    func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
        let buttonTitle = actionSheet.buttonTitle(at: buttonIndex)
        
        if buttonTitle == "拍照" {
            let pick = UIImagePickerController()
            pick.sourceType = UIImagePickerControllerSourceType.camera
            pick.delegate = self
            self.present(pick, animated: true, completion: nil)
        }else if buttonTitle == "从相册中选择" {
            let pick = UIImagePickerController()
            pick.sourceType = UIImagePickerControllerSourceType.photoLibrary
            pick.delegate = self
            self.present(pick, animated: true, completion: nil)
        }

    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let dic: NSDictionary = info as NSDictionary
        let image = dic.object(forKey: UIImagePickerControllerOriginalImage)
        photoArray.add(image!)
        photoCollectionView.frame = CGRect(x: 10, y: contentField.frame.maxY + 10, width: screenW - 20, height: getAddPhotoCollectionHeight(photoArray))
        photoCollectionView.reloadData()
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    //MARK: - text view delegate
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.characters.count == 0 {
            placeholderLabel.text = "提交您所要举报的内容（100字内)"
        }else{
            placeholderLabel.text = ""
            contentField.layer.borderColor = UIColor.init(hexString: "4e92df", alpha: 1.0).cgColor
            contentField.layer.borderWidth = 2
            contentField.layer.cornerRadius = 4
        }
        let length = textView.text.characters.count
        if length > 200 {
            
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
